package com.example.config;

import com.github.pagehelper.PageInterceptor;
import org.apache.ibatis.plugin.Interceptor;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;

import javax.sql.DataSource;
import java.util.Properties;

//@Configuration   // 导入到 SpringConfig 配置

//@PropertySource("classpath:jdbc.properties")   抽取到了 JdbcConfig
@MapperScan("com.example.dao")  // 推荐使用注解管理 Mapper
public class MyBatisConfig {


    // 分页插件拦截器
    @Bean
    public PageInterceptor pageInterceptor(){
        PageInterceptor pageInterceptor = new PageInterceptor();

        // 配置
        Properties properties = new Properties();
        properties.setProperty("value","true");

        pageInterceptor.setProperties(properties);

        return pageInterceptor;
    }


    @Autowired
    private PageInterceptor pageInterceptor;

    @Bean
    public SqlSessionFactoryBean sqlSessionFactory(DataSource dataSource) {

        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dataSource);
        sqlSessionFactoryBean.setTypeAliasesPackage("com.example.domain");

        sqlSessionFactoryBean.setPlugins(new Interceptor[]{pageInterceptor});

        return sqlSessionFactoryBean;
    }






    /*
     * 作了一些调整
     * 将数据源相关配置抽取到 JdbcConfig
     *
     * */

//    @Value("${jdbc.url}")
//    private String url;
//
//    @Value("${jdbc.driverClassName}")
//    private String driverClassName;
//
//    @Value("${jdbc.username}")
//    private String username;
//
//    @Value("${jdbc.password}")
//    private String password;
//
//
//    @Bean
//    public DataSource dataSource() {
//        DruidDataSource dataSource = new DruidDataSource();
//
//        dataSource.setDriverClassName(driverClassName);
//        dataSource.setUrl(url);
//        dataSource.setUsername(username);
//        dataSource.setPassword(password);
//
//        return dataSource;
//    }

//  推荐注解  @MapperScan("com.example.dao")
//    @Bean
//    public MapperScannerConfigurer mapperScannerConfigurer(){
//
//        MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();
//        mapperScannerConfigurer.setBasePackage("com.example.dao");
//        mapperScannerConfigurer.setSqlSessionFactoryBeanName("sqlSessionFactory");
//        return mapperScannerConfigurer;
//    }


}
/*
jdbc.driverClassName=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/ssm
jdbc.username=java_user
jdbc.password=1111
 */